<script setup>
import { computed, nextTick, onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { login, loginOut } from "../services/login";
import userInfo from "../views/login/UserInfo.vue";
import onlineChat from "../views/onlineChat/OnlineChat.vue";
import { bus } from "../mitt/mitt";
import { CollectionTag } from "@element-plus/icons-vue";
import { tokenStatistics } from "../services/chat";
import * as echarts from "echarts";
import { notReadCount, getMsgList, readAll, findById } from "../services/msg";
import { Bell, ChatRound } from "@element-plus/icons-vue";
import MsgDetails from "../components/MsgDetails.vue";
import { ElNotification } from "element-plus";
import { elNotificationStore } from "../store/LoginSuccessStore";
import { isLoginStore } from "../store/IsLoginStore";
const isLogin = isLoginStore();
const elNotStore = elNotificationStore();
const router = useRouter(false);
const userData = computed(() => {
  return JSON.parse(localStorage.getItem("userData"));
});
const f_handleCommand = function (handleCommand) {
  if (handleCommand === "exit") {
    if (isLogin.getIsLoginFlag) {
      loginOut()
        .then((res) => {
          localStorage.removeItem("Authorization");
          localStorage.removeItem("userData");
          router.go(0);
        })
        .catch((error) => {});
    }
  } else if (handleCommand === "personalCenter") {
    bus.emit("exitPersonalCenter", "");
  }
};
const type = ref(1);
const getLineChart = () => {
  const tokens = document.getElementById("tokens");
  echarts.dispose(tokens);
  const myChart = echarts.init(tokens);
  tokenStatistics(type.value)
    .then((res) => {
      let x = [];
      let y = [];
      res.data.forEach((i) => {
        x.push(i.time);
        y.push(i.tokens);
      });

      let option = {
        title: {
          text: "AI-TOKENS使用量",
          left: "center",
        },
        xAxis: {
          data: x,
        },
        // legend: {
        //   data: x,
        // },
        tooltip: {
          trigger: "axis",
        },
        yAxis: {},
        series: [
          {
            data: y,
            type: "line",
            smooth: true,
          },
        ],
      };
      myChart.setOption(option);
    })
    .catch((err) => {});
};
//消息
const notReadMsgNum = ref(0);
const getNotReadMsgNum = () => {
  notReadCount()
    .then((res) => {
      notReadMsgNum.value = res.data;
    })
    .catch((err) => {});
};
const msgList = ref([]);
const msgListGet = () => {
  let query = {
    isRead: 0,
    current: 1,
    size: 4,
  };
  getMsgList(query)
    .then((res) => {
      msgList.value = res.data.records;
    })
    .catch((err) => {});
};
const allRead = () => {
  readAll()
    .then((res) => {
      if (res.data) {
        msgListGet();
        getNotReadMsgNum();
      }
    })
    .catch((err) => {});
};
const msgDetail = (id) => {
  //获取消息内容
  findById(id)
    .then((res) => {
      bus.emit("msgDetail", res.data);
      getNotReadMsgNum();
    })
    .catch((res) => {});
};

// 在线聊天打开开关
const openOnlineChat = () => {
  bus.emit("openOnline", true);
};
onMounted(() => {
  getNotReadMsgNum();
  nextTick(() => {
    const isShow = elNotStore.getIsShow;
    if (isShow == 1) {
      ElNotification({
        title: "系统消息",
        message:
          "欢迎您：" + (userData.value.fullName || userData.value.username),
        type: "success",
      });
      elNotStore.setIsShow(0);
    }
  });
});
</script>

<template>
  <div class="header-container">
    <el-popover
      placement="top-start"
      title="消耗Token数"
      :width="800"
      trigger="hover"
      @show="getLineChart"
    >
      <template #reference>
        <el-icon style="font-size: 20px"><CollectionTag /></el-icon>
      </template>
      <div>
        <el-radio-group v-model="type" @change="getLineChart">
          <el-radio :label="1" size="large">天</el-radio>
          <el-radio :label="2" size="large">月</el-radio>
        </el-radio-group>
        <!-- 折线图 -->
        <div id="tokens" style="height: 300px; width: 800px"></div>
      </div>
    </el-popover>
    <!-- <div class="onlineChat" @click="openOnlineChat">
      <el-icon style="font-size: 20px"><ChatRound /></el-icon>在线聊天
    </div>
    <onlineChat /> -->
    <div class="r-content">
      <el-popover
        placement="bottom-end"
        :width="300"
        trigger="click"
        @show="msgListGet"
      >
        <template #reference>
          <el-badge :value="notReadMsgNum" :max="99" class="item">
            <el-icon class="icon"><Bell /></el-icon>
          </el-badge>
        </template>
        <div class="msg">
          <span style="font-size: 15px">通知</span>
          <span @click="allRead" class="all-read-span">全部已读</span>
          <el-divider class="divider"></el-divider>
          <div v-if="msgList.length > 0">
            <div
              v-for="msg in msgList"
              :key="msg.id"
              @click="msgDetail(msg.id)"
            >
              <span>{{ msg.titile }}</span>
              <br />
              <div style="margin-bottom: 10px"></div>
              <span v-if="msg.msgType == 1">系统通知</span>
              <span v-else>用户咨询</span>
              <span style="float: right">{{ msg.createTime }}</span>
              <el-divider class="divider"></el-divider>
            </div>
          </div>
          <el-empty v-else description="暂无未读消息" />
        </div>
      </el-popover>
      <el-dropdown @command="f_handleCommand" class="head">
        <span>
          <el-avatar
            class="user_head"
            v-if="
              userData == null ||
              userData.headPic === null ||
              userData.headPic === ''
            "
            icon="el-icon-user-solid"
          ></el-avatar>
          <img v-else :src="userData.headPic" class="user_head" />
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="personalCenter"
              >个人中心</el-dropdown-item
            >
            <el-dropdown-item command="exit">退出</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <userInfo />
    <MsgDetails />
  </div>
</template>

<style lang="less" scoped>
.header-container {
  height: 60px;
  background-color: #fffefe;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  border-left: 1px solid #e5e7eb;
  border-right: 1px solid #e5e7eb;
  border-bottom: 2px solid #e5e7eb;
  .onlineChat:hover {
    color: rgb(57, 149, 255);
  }
}
.r-content {
  display: flex;
  justify-content: center;
  align-items: center;
  .item {
    margin-top: 6px;
    .icon {
      font-size: 25px;
    }
  }
  .item:hover {
    color: rgb(57, 149, 255);
  }
  .head {
    .user_head {
      margin-left: 25px;
      width: 40px;
      height: 40px;
      border-radius: 50%;
    }
  }
}
.divider {
  margin-top: 10px;
  margin-bottom: 10px;
}
.all-read-span {
  font-size: 15px;
  margin-left: 150px;
  color: rgb(57, 149, 255);
}
.all-read-span:hover {
  cursor: pointer;
  color: red;
}
</style>
